<?php

namespace App\Http\Controllers;

use App\Jobs\CrawlKeys;
use App\Models\JDBook;
use App\Models\Spider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SpiderController extends Controller
{
    public function create(Request $request){
        $key=$request['key'];
        if (!$key){
            return response()->json([
                'message' => 'Key required.'
            ], 400);
        }

        foreach ($request->platform as $type){
            $spider=new Spider();
            $spider->key=$key;
            $spider->status='queuing';
            $spider->type=$type;
            $spider->max_count=$request->maxCount;
            $spider->save();
            CrawlKeys::dispatch($spider->id);
        }

        return response()->json([
            'message' => 'Created.',
            'id'=>$spider->id
        ]);
    }

    public function getAll(){
        return Spider::withCount('jd_books')->withCount('dd_books')->with('book')->orderByDesc('id')->paginate(10);
    }

    public function cancel(Request $request){
        $spider=Spider::findOrFail($request->id);
        if ($spider->status=='running' || $spider->status=='queuing'){
            $spider->status='cancelling';
            $spider->save();
            return [
                'message'=>'Cancelling',
            ];
        }
        $status=$spider->status;
        return response()->json([
            'message'=>"Spider is {$status}."
        ], 400);
    }

    public function getKeys(){
        return Spider::query()->groupBy('key')->where('type', '!=', 'comment')->selectRaw("`key`, min(id) as id")->orderByDesc('id')->limit(10)->get();
    }

    public function getSpidersByKey(Request $request)
    {
        $queryOrder = "CASE WHEN status = 'finished' THEN 1 ";
        $queryOrder .= "ELSE 2 END";

        $jd_spider=Spider::where('key', $request->key)
            ->where('type', 'jd')
            ->withCount('jd_books')
            ->orderByRaw($queryOrder)
            ->orderByDesc('jd_books_count')
            ->orderByDesc('id')
            ->first();

        $dd_spider=Spider::where('key', $request->key)
            ->where('type', 'dd')
            ->withCount('dd_books')
            ->orderByRaw($queryOrder)
            ->orderByDesc('dd_books_count')
            ->orderByDesc('id')
            ->first();

        return [
            "jd_spider" => $jd_spider,
            "dd_spider" => $dd_spider,
        ];
    }
}
